'''
Description: 
Author: Zilu
Date: 2021-11-17 15:28:38
Version: 
LastEditTime: 2021-11-17 19:15:42
LastEditors: Zilu
'''

# 要操作关系数据库，首先需要连接到数据库，一个数据库连接称为Connection；
# 连接到数据库后，需要打开游标，称之为Cursor，通过Cursor执行SQL语句，然后，获得执行结果。
import sqlite3
conn = sqlite3.connect('test.db')
cursor = conn.cursor()

cursor.execute('create table if not exists user(id varchar(20) primary key, name varchar(20))')
cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')')
# 获得插入的行数
cursor.rowcount
cursor.close()
# 一定要提交事务
conn.commit()
# 也别忘了关闭连接
conn.close()

# 取数据
conn = sqlite3.connect('test.db')
cursor = conn.cursor()
cursor.execute('select * from user where id=?',('1',))
values = cursor.fetchall()
values
cursor.close()
conn.close()

# 练习：编写函数在sqlite中根据分数段查找指定名字
import os, sqlite3

db_file = os.path.join(os.path.dirname(__file__), 'test.db')
if os.path.isfile(db_file):
    os.remove(db_file)

# 初始数据:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)')
cursor.execute(r"insert into user values ('A-001', 'Adam', 95)")
cursor.execute(r"insert into user values ('A-002', 'Bart', 62)")
cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)")
cursor.close()
conn.commit()
conn.close()

def getScoreIn(low, high):
    # try-catch 处理
    try:
        conn = sqlite3.connect(db_file)
        cursor = conn.cursor()
        cursor.execute(r'select name from user where score>=? and score<=?', (low, high))
        values = cursor.fetchall()
    except sqlite3.Warning or sqlite3.Error as e:
        print(e)
    finally:
        cursor.close()
        conn.commit()
        conn.close()
    return [name[0] for name in values]

# 测试:
assert getScoreIn(80, 95) == ['Adam'], getScoreIn(80, 95)
assert getScoreIn(60, 80) == ['Bart', 'Lisa'], getScoreIn(60, 80)
assert getScoreIn(60, 100) == ['Adam', 'Bart', 'Lisa'], getScoreIn(60, 100)

print('Pass')



